package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {


    @Override
    public ResponseResult login(WmUserDTO dto) {
        // 1 检查校验
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"账号密码不能为空");
        }
        // 2 查询自媒体用户
        WmUser one = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(
                WmUser::getName, dto.getName()
        ));
        if(one==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"账号需要登录");
        }

        // 状态码是否正常
        if (AdminConstants.PASS_AUTH != one.getStatus().intValue()) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"账号异常");
        }
        // 校验密码
        String pwd = DigestUtils.md5DigestAsHex((dto.getName()+one.getSalt()).getBytes(StandardCharsets.UTF_8));

        if (!pwd.equals(one.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入错误");
        }
        Map<String,Object> map=new HashMap<>();
        //生成 token
        String token = AppJwtUtil.getToken(Long.valueOf(one.getId()));
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(one,wmUserVO);
        // 3 返回jwt结果
        map.put("user",wmUserVO);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
